// ***********************************************
// 这个文件用于定义自定义命令并覆盖现有命令
// ***********************************************

// 登录命令
Cypress.Commands.add('login', (email, password) => {
  cy.visit('/login');
  cy.get('#email').type(email);
  cy.get('#password').type(password);
  cy.get('form').submit();
  cy.url().should('eq', Cypress.config().baseUrl + '/');
});

// 注册命令
Cypress.Commands.add('register', (username, email, password) => {
  cy.visit('/register');
  cy.get('#username').type(username);
  cy.get('#email').type(email);
  cy.get('#password').type(password);
  cy.get('#confirmPassword').type(password);
  cy.get('form').submit();
  cy.url().should('eq', Cypress.config().baseUrl + '/');
});

// 上传文件命令
Cypress.Commands.add('uploadFile', (selector, fileName, fileType = 'text/plain') => {
  cy.get(selector).then(subject => {
    cy.fixture(fileName, 'base64').then(content => {
      const testFile = new File([Cypress.Blob.base64StringToBlob(content)], fileName, {
        type: fileType
      });
      const dataTransfer = new DataTransfer();
      dataTransfer.items.add(testFile);
      
      subject[0].files = dataTransfer.files;
      return cy.wrap(subject).trigger('change', { force: true });
    });
  });
});

// 通过API登录并设置token命令
Cypress.Commands.add('loginByApi', (email, password) => {
  cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/users/login`,
    body: {
      email,
      password
    }
  }).then((response) => {
    expect(response.status).to.eq(200);
    expect(response.body).to.have.property('token');
    
    // 设置localStorage
    localStorage.setItem('userToken', response.body.token);
    localStorage.setItem('userData', JSON.stringify(response.body.user));
    
    // 刷新页面以应用新的token
    cy.visit('/');
  });
});

// 创建文档命令
Cypress.Commands.add('createDocument', (title, description, fileName) => {
  cy.visit('/documents');
  cy.contains('上传文档').click();
  cy.get('#title').type(title);
  cy.get('#description').type(description);
  cy.uploadFile('input[type=file]', fileName);
  cy.get('form').submit();
  cy.contains(title).should('be.visible');
});

// 等待加载状态消失
Cypress.Commands.add('waitForLoading', () => {
  cy.get('.loading-indicator', { timeout: 10000 }).should('not.exist');
});

// 检查元素是否可见并可点击
Cypress.Commands.add('shouldBeClickable', (selector) => {
  cy.get(selector)
    .should('be.visible')
    .should('not.be.disabled')
    .should('have.css', 'pointer-events', 'auto');
});

// 检查表单验证错误
Cypress.Commands.add('checkValidationError', (fieldSelector, errorMessage) => {
  cy.get(fieldSelector).then($field => {
    // 检查字段是否有错误类
    cy.wrap($field).should('have.class', 'is-invalid');
    
    // 检查错误消息
    cy.get(`${fieldSelector} ~ .invalid-feedback, ${fieldSelector} + .invalid-feedback`)
      .should('be.visible')
      .and('contain', errorMessage);
  });
});

// 测试API命令 - 设置测试数据
Cypress.Commands.add('setupTestData', (options = {}) => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/complete-setup`,
    body: options
  }).then((response) => {
    expect(response.status).to.eq(200);
    return response.body.data;
  });
});

// 测试API命令 - 清理测试数据
Cypress.Commands.add('cleanupTestData', () => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/cleanup`
  }).then((response) => {
    expect(response.status).to.eq(200);
  });
});

// 测试API命令 - 重置测试数据
Cypress.Commands.add('resetTestData', (options = {}) => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/reset`,
    body: options
  }).then((response) => {
    expect(response.status).to.eq(200);
    return response.body.userId;
  });
});

// 测试API命令 - 创建测试文档
Cypress.Commands.add('createTestDocument', (options = {}) => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/documents`,
    body: options
  }).then((response) => {
    expect(response.status).to.eq(201);
    return response.body.documentId;
  });
});

// 测试API命令 - 创建测试卡片
Cypress.Commands.add('createTestCards', (options = {}) => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/cards`,
    body: options
  }).then((response) => {
    expect(response.status).to.eq(201);
    return response.body.cards;
  });
});

// 测试API命令 - 创建测试练习题
Cypress.Commands.add('createTestExercises', (options = {}) => {
  return cy.request({
    method: 'POST',
    url: `${Cypress.env('apiUrl')}/api/testing/exercises`,
    body: options
  }).then((response) => {
    expect(response.status).to.eq(201);
    return response.body.exercises;
  });
}); 